<template>
  <div id="progress-loop" ref="chartDom" style="width: 100%; height: 100%"></div>
</template>

<script setup lang="ts" name="dataScreen">
import { ref, onMounted, onBeforeUnmount, nextTick, onUpdated } from "vue";
import { debounce } from "@/utils";
import * as echarts from "echarts";
import { countSize } from "@/utils/utils";


const props = defineProps({
  reportDuty: {
    type: Array,
    default: () => [],
  },
});

const chartDom = ref(null);
let myChart = null;

// 数据处理函数
const processData = () => {
  console.log('props.reportDuty', props.reportDuty);
  const xAxisData = [];
  const seriesMap = {
    arrivedQty: { name: "到岗人数", data: [], color: "#91cc75" },
    leaveQty: { name: "请假人数", data: [], color: "#FFB5C5" },
    staHolidayQty: { name: "轮休人数", data: [], color: "#FFD700" },
    notArrivedQty: { name: "未到岗人数", data: [], color: "#FF6347" },
  };

  // 如果 reportDuty 不是数组，则直接返回空数据
  if (!Array.isArray(props.reportDuty)) {
    return { xAxisData, series: [] };
  }

  // 创建一个 map 用来存储每个团队的指标数据
  const teamDataMap = {};

  // 遍历每个工艺 process
  props.reportDuty.forEach((process) => {
    // 对每个团队 team 进行处理
    process.teamAttendModels.forEach((team) => {
      const teamName = team.teamName.replace("生产一部", "").replace("临时调度", "");

      // 如果 teamName 不在 xAxisData 中，则添加
      if (!xAxisData.includes(teamName)) {
        xAxisData.push(teamName);

        // 初始化每个团队的指标数据
        Object.keys(seriesMap).forEach(key => {
          teamDataMap[teamName] = teamDataMap[teamName] || {
            arrivedQty: 0,
            leaveQty: 0,
            staHolidayQty: 0,
            notArrivedQty: 0,
          };
        });
      }

      // 更新团队的指标数据
      teamDataMap[teamName].arrivedQty += team.attendModels.arrivedQty;
      teamDataMap[teamName].leaveQty += team.attendModels.leaveQty;
      teamDataMap[teamName].staHolidayQty += team.attendModels.staHolidayQty;
      teamDataMap[teamName].notArrivedQty += team.attendModels.notArrivedQty;
    });
  });

  // 为每个指标创建数据
  Object.keys(seriesMap).forEach(key => {
    const seriesData = [];

    xAxisData.forEach(teamName => {
      seriesData.push(teamDataMap[teamName] ? teamDataMap[teamName][key] : 0); // 如果没有数据则为 0
    });

    seriesMap[key].data = seriesData;
  });

  // 将 seriesMap 转换成数组格式
  const series = Object.keys(seriesMap).map(key => ({
    name: seriesMap[key].name,
    type: 'bar',
    stack: '总量', // 所有系列都堆叠在一起
    data: seriesMap[key].data,
    itemStyle: {
      color: seriesMap[key].color,
    },
    label: {
      normal: {
        show: true,
        position: "inside", // 设置标签位置为 "inside" 以居中显示
        formatter: function (params) {
          return params.value === 0 ? '' : params.value; // 如果值为 0 则不显示
        },
        textStyle: {
          color: "#fff",
          // fontSize: countSize(0.1),
        },
      },
    },
  }));

  return { xAxisData, series };
};



// 图表配置函数
const getChartOption = (data) => ({
  tooltip: {
    trigger: "axis",
    axisPointer: { type: "shadow" },
    formatter: (params) => {
      let tooltipStr = `${params[0].axisValue}<br/>`;
      params.forEach((item) => {
        if (item.value !== 0) {
          tooltipStr += `${item.marker} ${item.seriesName}: ${item.value}<br/>`;
        }
      });
      return tooltipStr;
    },
  },
  title: {
    text: '班组人员出勤数据',
    textStyle: {
      //图例文字的样式
      fontSize: countSize(0.14),
      color: "#fff",
    },
    left: "left",
    top: "0",
  },
  legend: {
    right: '0', // 将图例放在右侧，可以根据需要调整位置
    textStyle: {
      color: '#FFFFFF', // 设置文字颜色为白色
      fontSize: 8, // 设置字体大小，您可以根据需要调整此值
    },
    itemHeight: 8, // 设置图例项的高度（可选）
    itemWidth: 8, // 设置图例项的宽度（可选）
  },
  grid: {
    left: "4%",
    right: "2%",
    bottom: '0%',
    top: '10%',
    containLabel: true,
  },
  xAxis: {
    type: "category",
    data: data.xAxisData,
    boundaryGap: true, // 确保柱子居中
    axisTick: {
      //坐标轴刻度相关设置。
      show: false,
    },
    axisLabel: {
      algin: 'center',
      interval: 0,
      rotate: 50,
      textStyle: { color: "#FFFFFF", fontSize: 10 },
    },
  },
  yAxis: {
    type: "value",
    min: 0, // 设定最小值
    axisLabel: {
      align: 'center',
      textStyle: { color: "#FFFFFF" }
    },
    axisTick: {
      show: false,
    },
    splitLine: {
      show: true,
      lineStyle: {
        color: ["#FFFFFF"],
        opacity: 0.06,
      },
    },
  },
  series: data.series,
});

// 初始化或更新图表
const initChart = () => {
  const data = processData(); // 处理数据
  const options = getChartOption(data); // 生成图表配置

  // 判断是否已经初始化图表
  if (!myChart) {
    myChart = echarts.init(chartDom.value);
  }
  myChart.setOption(options); // 设置新的图表配置
};

// 窗口大小变化时重新渲染图表
const resizeChart = debounce(() => {
  if (myChart) {
    myChart.resize();
  }
}, 100);

// 挂载时初始化图表
onMounted(() => {
  nextTick(() => {
    initChart(); // 初次渲染图表
    window.addEventListener("resize", resizeChart); // 监听窗口变化
  });
});

// 组件更新时重新处理并渲染图表
onUpdated(() => {
  console.log('props.reportDuty updated:', props.reportDuty);
  if (Array.isArray(props.reportDuty) && props.reportDuty.length > 0) {
    initChart(); // 重新处理数据并更新图表
  }
});

// 卸载时移除事件监听器并释放资源
onBeforeUnmount(() => {
  if (myChart) {
    window.removeEventListener("resize", resizeChart); // 移除监听器
    myChart.dispose(); // 释放图表实例资源
  }
});
</script>
